package com.shopping.shoppingdemo.controller;


import cn.idev.excel.ExcelWriter;
import cn.idev.excel.FastExcel;
import cn.idev.excel.write.metadata.WriteSheet;
import com.shopping.shoppingdemo.domain.dto.RequestCountExcelDO;
import com.shopping.shoppingdemo.domain.po.RequestCountDO;
import com.shopping.shoppingdemo.domain.vo.PageParam;
import com.shopping.shoppingdemo.enums.UserRole;
import com.shopping.shoppingdemo.service.RequestCountService;
import com.shopping.shoppingdemo.utils.ParallelExportUtil;
import com.shopping.shoppingdemo.utils.annotion.Permission;
import com.shopping.shoppingdemo.utils.converter.StatisticsConverter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 用于一些功能测试的入口，默认都使用从库，不支持修改数据
 *
 * @author Yandel
 * @date 2025/10/10
 */
@Slf4j
//@DsAno(MasterSlaveDsEnum.SLAVE)
@RestController
@RequestMapping(path = "/test")
public class TestController {
//    private AtomicInteger cnt = new AtomicInteger(1);


    @Autowired
    private RequestCountService requestCountService;

    @PostMapping(path = "post")
    public String testPost(@RequestBody String body) {
        log.info("收到测试 POST 请求，body={}", body);
        return "收到 POST 请求，body=" + body;
    }

    // 准备使用 FastExcel 批量导出 500万条数据
/*
    @Permission(role = UserRole.ADMIN)
    @GetMapping(path = "exportBatch")
    public void exportBatch(HttpServletResponse response) throws IOException {
        OutputStream outputStream = response.getOutputStream();

        // 查出总数量
        long total = requestCountService.count();

        // 每页大小
        int pageSize = 100000; // 每页 1 万条数据

        // 每个 Sheet 容纳数据条数
        int sheetSize = 1000000; // 每个 Sheet 100 万条数据
        int sheetCount = (int) (total / sheetSize + (total % sheetSize == 0 ? 0 : 1));

        // 文件名
        String fileName = URLEncoder.encode("批量导出测试.xlsx", "UTF-8").replaceAll("\\+", "%20");

        // 设置响应头
        response.reset();
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName);

        // 开始导出
        try (ExcelWriter excelWriter = FastExcel.write(outputStream, RequestCountExcelDO.class).build()) {
            for (int sheetIndex = 0; sheetIndex < sheetCount; sheetIndex++) {
                // 命名 Sheet
                WriteSheet sheet = FastExcel.writerSheet(sheetIndex, "sheet" + (sheetIndex + 1)).build();

                // 查询数据
                for (int pageIndex = 0; pageIndex < sheetSize / pageSize; pageIndex++) {
                    // 第一页是从 0-9999，第二页是从 10000-19999
                    int offset = sheetIndex * sheetSize + pageIndex * pageSize + 1;
                    // TODO 自定义线程池+ CountDownLatch 进行优化
                    List<RequestCountDO> data = requestCountService.listRequestCount(PageParam.newPageInstance(offset, pageSize));
                    List<RequestCountExcelDO> list = StatisticsConverter.convertToRequestCountExcelDOList(data);
                    excelWriter.write(list, sheet);
                    log.info("导出第 {} 页数据，目前是第{} 条数据", pageIndex, offset);
                    log.info("总共 {} 条，已经导出 {} 条", total, Math.min(offset + pageSize - 1, total));
                }

            }
        }
    }
*/



// 将原来的循环替换为如下调用（需要导入 ParallelExportUtil）
    @Permission(role = UserRole.ADMIN)
    @GetMapping(path = "exportBatch")
    public void exportBatch(HttpServletResponse response) throws IOException {
        OutputStream outputStream = response.getOutputStream();

        long total = requestCountService.count();
        int pageSize = 100000;
        int sheetSize = 1000000;

        String fileName = URLEncoder.encode("批量导出测试.xlsx", "UTF-8").replaceAll("\\+", "%20");
        response.reset();
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName);

        // 并发抓取线程数可按机器调整，例如 8
        ParallelExportUtil.export(requestCountService, total, pageSize, sheetSize, outputStream, 8);
    }

}
